from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

boston = load_boston()
# 房价数据分割
x_train, x_test, y_train, y_test = train_test_split(boston.data,boston.target)

# 训练与测试数据标准化处理
ss = StandardScaler()
# 训练集特征值转换
x_train = ss.fit_transform(x_train)
# 测试集特征值转换
x_test = ss.transform(x_test)

# 解决回归问题，如果对特征值进行标准化，对目标值也需要
ss_y = StandardScaler()
# 对训练集的模板值的标准化，不能使用原来对特征值的StandardScaler
# Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.
y_train = ss_y.fit_transform(y_train.reshape(-1,1))

# 使用梯度下降求解回归系数
sgd = SGDRegressor()

sgd.fit(x_train, y_train)
sgd_predict = sgd.predict(x_test)
# 由于x_test已经标准化，预测的结果是标准化的结果，需要进行逆标准化才能得到最终的结果
# print(lr_predict) # 发现有负数
print(ss_y.inverse_transform(sgd_predict))
print("梯度下降得到的回归系数",sgd.coef_)  #得到一个列表

sgd_error = mean_squared_error(y_true=y_test,y_pred=ss_y.inverse_transform(sgd_predict))
print(sgd_error)

